﻿// -----------------------------------------------------------------------
// <copyright file="RequestSigning.cs" company="TaskyMedia LLC">
//  Copyright (c) TaskyMedia LLC
// </copyright>
// -----------------------------------------------------------------------

namespace SohpShared
{
    using System;
    using System.Globalization;
    using System.Security.Cryptography;
    using System.Text;

    /// <summary>
    /// Provides the mechanism to generate request signatures.
    /// </summary>
    public static class RequestSigning
    {
        /// <summary>
        /// Generates a request signature.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <param name="adjustedTimestamp">The adjusted timestamp.</param>
        /// <param name="sessionSecret">The session secret.</param>
        /// <returns>Returns the request signature.</returns>
        public static string GenerateSignature(string operation, long adjustedTimestamp, long sessionSecret)
        {
            string toHashValue = string.Format(CultureInfo.InvariantCulture, "{0}|{1}|{2}", operation, adjustedTimestamp, sessionSecret);

            using (SHA1Managed hashAlgo = new SHA1Managed())
            {
                return hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(toHashValue)).ToHexString();
            }
        }

        /// <summary>
        /// Converts a byte array to a string of hexadecimal characters.
        /// </summary>
        /// <param name="inputValue">The raw string bytes.</param>
        /// <returns>Returns a string of hexadecimal characters.</returns>
        public static string ToHexString(this byte[] inputValue)
        {
            if (inputValue != null && inputValue.Length > 0)
            {
                string hashString = string.Empty;

                for (int i = 0; i < inputValue.Length; i++)
                {
                    hashString += Convert.ToString(inputValue[i], 16).PadLeft(2, '0');
                }

                return hashString.PadLeft(32, '0');
            }
            else
            {
                return null;
            }
        }
    }
}
